﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using ApplicationGenerator.CommonModule;

namespace WCFS
{
    //TODO: KONIECZNIE NAPRAWIC OBSLUGE BLEDOW (TRY,CATCH)

    public class WorkflowFactory
    {

        #region Variables

        private static WorkflowFactory instance = null;

        private static Dictionary<string, Type> registeredWorkflowTypes = new Dictionary<string, Type>();
        private static string configurationFile;

        #endregion

        #region Construction

        WorkflowFactory()
        {
                
        }

        static WorkflowFactory()
        {
            
        }

        #endregion

        #region Properties
        
        public static WorkflowFactory getInstance( string fileName )
        {
            if (instance == null)
            {
                instance = new WorkflowFactory();
                instance.ConfigurationFile = fileName;
                RegisterWorkflowsFromFile();
                return instance;
            }
            else
            {
                instance.ConfigurationFile = fileName;
                RegisterWorkflowsFromFile();
                return instance;
            }
        }

        /// <summary>
        /// Holds configuration file that is containing mapping between dll file with workflow,
        /// and it's unique name
        /// </summary>
        public string ConfigurationFile
        {
            get { return configurationFile; }
            set {configurationFile = value; }
        }

        #endregion

        /// <summary>
        /// After setting config file string, start registering workflows
        /// </summary>
        /// <returns></returns>
        public static bool RegisterWorkflowsFromFile()
        {
            
            if (File.Exists(configurationFile))
            {
                try
                {
                    XmlConfigMaker config = new XmlConfigMaker(configurationFile);

                    List<ConfigEntry> list = config.GetAllEntries();

                    foreach (ConfigEntry entry in list)
                    {
                        //load assembly ..
                        if (entry.Name == "workflow")
                        {
                            Assembly modelsAssembly = Assembly.LoadFile(entry.GetAttributeByName("dll").Value);
                            foreach (Type type in modelsAssembly.GetTypes())
                            {
                                //every generator workflow should be derived from GeneratorSequentialWorkflow
                                //no other classes should be considered.
                                if ((typeof(WorkflowLibrary.GeneratorSequentialWorkflow)).IsAssignableFrom(type))
                                {
                                    try
                                    {
                                        registeredWorkflowTypes.Add(entry.Value, type);
                                    }
                                    catch (Exception)
                                    {
                                    }
                                }
                            }
                        }
                    }
                }
                catch (Exception)
                {
                    
                }
                
                return true;
            }
            else
            {
                //File not exists!
                return false;
            }
        }

        /// <summary>
        /// Creates new workflow - basing on typeId 
        /// </summary>
        /// <param name="id"> type id for workflow </param>
        /// <returns>GeneratorSequentialWrokflow</returns>
        public WorkflowLibrary.GeneratorSequentialWorkflow GetWorkflow(string typeId)
        {
            Type t = registeredWorkflowTypes[typeId];
            WorkflowLibrary.GeneratorSequentialWorkflow MyObj = (WorkflowLibrary.GeneratorSequentialWorkflow)Activator.CreateInstance(t);
            return MyObj;
        }

        /// <summary>
        /// returns type of selected workflow (by name)
        /// </summary>
        /// <param name="typeId">unique indetifier of worflow type</param>
        /// <returns>Type of Workflow</returns>
        public Type GetWorkflowType(string typeId)
        {
            try
            {
                return registeredWorkflowTypes[typeId];
            }
            catch (ArgumentNullException)
            {
                throw new WCFServiceException("could not find process identified by key: "+ typeId);
            }
        }

    }
}
